package cn.tedu.d2_thread;
/*
 本类测试线程锁的用法
 */
public class Test1_ThreadLock {
    public static void main(String[] args) {

        SaleTicket target=new SaleTicket();

        //参数target传入Thread
        Thread t1=new Thread(target,"一号");
        Thread t2=new Thread(target,"二号");
        Thread t3=new Thread(target,"三号");
        Thread t4=new Thread(target,"四号");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

}
class SaleTicket implements Runnable{

    static int tickets=100;
    //Object o=new Object();
    @Override
    synchronized public void run() {

        while (true){
            synchronized (this) {
                if(tickets>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + tickets--);
                }
                if (tickets <= 0) break;
            }
        }
    }
}
